import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import { View, Text, Button, Image, ScrollView } from '@tarojs/components';
import './index.scss'
import { getFundExaminationAnswerDetail } from '@/services/api/xiaoyiAccExam';
import { number } from '@/components/echarts-taro3-react/ec-canvas/echarts';
import { Popup, Toast } from '@antmjs/vantui';
import { askQuestion, getQuestionAnswer } from '@/services/api/common';

class XiaoYiAnalysis extends Component {

    config = {
        navigationBarTitleText: ''
    }

    state = {
        type: 1,//type 2 : 结果页  1  答题页
        currentInex: 0,
        scrollLeft: 0,
        questions: [],// {'name' data}
        showPopUP: false,
        showXiaoyiPopUP: false,
        xiaoyiPopupType: 2, // 1 答案 2 名词解析
        xiaoyiCurrentAnswerxi: '', // 当前名词
        xiaoyiAnswerxi: {},// 答案提示
        xiaoyiNounCurrentNoun: '', // 当前名词
        xiaoyiNounPairMap: {}, // 所有保存了的名词以及解析
        requestCount: 0,
    }

    componentWillMount() {

        // type 2 : 结果页  1  答题页
        // Taro.preload({'type':2,'data':value})
        var preloadData: any = Taro.getCurrentInstance().preloadData
        console.log(preloadData)
        this.requestData(preloadData)

        Taro.setNavigationBarTitle({
            title: preloadData['name']
        })

        Taro.preload({})
    }

    componentDidMount() { }
    componentWillReceiveProps(nextProps, nextContext) { }
    componentWillUnmount() { }

    requestData(preloadData) {
        var detail_ids = ''
        for (let index = 0; index < preloadData['data'].length; index++) {
            if (detail_ids.length === 0) {
                detail_ids = preloadData['data'][index]
            } else {
                detail_ids = detail_ids + ',' + preloadData['data'][index]
            }
        }

        getFundExaminationAnswerDetail(detail_ids).then((resp) => {
            if (resp.code === 200) {
                this.setState({ questions: resp.data })
            }
        })

    }

    onScrollEndd(e) {
        const { screenWidth } = Taro.getSystemInfoSync()
        var index = Math.round(e.detail.scrollLeft / screenWidth)
        this.setState({ currentInex: index })
    }

    onClose() {
        this.setState({ showPopUP: false })
    }

    showQuestionPopup() {
        this.setState({ showPopUP: true })
    }

    gotoIndexPage(index) {
        const { screenWidth } = Taro.getSystemInfoSync()
        // 没有效果
        // this.scrollViewRef.current.scrollTo({
        //     scrollLeft: screenWidth*currentInex,
        //     behavior: 'smooth'
        // })
        this.setState({ scrollLeft: screenWidth * index, showPopUP: false, })
    }

    onXiaoyiClose() {
        this.setState({ showXiaoyiPopUP: false })
    }


    handleSpanClick(keyword) {
        console.log(keyword)
        const { xiaoyiNounPairMap } = this.state

        this.setState({
            requestCount: 0
        })
        if (xiaoyiNounPairMap[keyword] !== undefined) {
            this.setState({ xiaoyiNounCurrentNoun: keyword, showXiaoyiPopUP: true, xiaoyiPopupType: 2 })
            return
        }

        var tempprompt = keyword;
        var currentDate = new Date();  // 当前日期
        var requestId = 'ydt' + currentDate.getTime() + 'tx'
        askQuestion(tempprompt, requestId).then((resp) => {
            if (resp.code === 200) {
                this.setState({ showXiaoyiPopUP: true, xiaoyiPopupType: 2, xiaoyiNounCurrentNoun: keyword, })
                this.timeBox = setInterval(() => {
                    console.log(this.timeBox);
                    const { requestCount, } = this.state
                    console.log(requestCount);
                    if (requestCount > 10) {
                        clearTimeout(this.timeBox);
                        Toast.show('人类的问题太多了！我需要休息一下再回复您');
                        return
                    }
                    var map = JSON.parse(resp.data)
                    this.requestKeywordsAnswer(keyword, map.data)
                    this.setState({
                        requestCount: requestCount + 1
                    })
                }, 2000);
            }
        })

    }

    timeBox;
    /**
     * 
     * @param requestId 
     * @returns 
     */
    requestKeywordsAnswer(keyword, requestId) {
        const { xiaoyiNounPairMap } = this.state

        getQuestionAnswer(requestId).then((resp) => {
            console.log(resp.data)
            if (resp.code === 200) {
                console.log("======")
                //字符串 转 map
                var map = JSON.parse(resp.data)
                console.log(map)

                if (map.code === 200) {
                    if (map['msg'] === '人类的问题太多了！' || map['msg'] === '人类的问题太多了！我需要休息一下再回复您') { } else {
                        console.log('我在哪里')
                        clearTimeout(this.timeBox);
                        xiaoyiNounPairMap[keyword] = map['msg']
                        this.setState({ showXiaoyiPopUP: true, xiaoyiNounCurrentNoun: keyword, xiaoyiNounPairMap: xiaoyiNounPairMap, xiaoyiPopupType: 2 })
                    }
                } else {

                }
            } else {

            }
        })
    }

    render() {
        const { questions, scrollLeft, currentInex, showPopUP, showXiaoyiPopUP, xiaoyiPopupType, xiaoyiNounCurrentNoun, xiaoyiNounPairMap, xiaoyiCurrentAnswerxi, requestCount } = this.state
        return (
            <View className='page'>
                <View className='head'>
                    <View className='heade-type'>单选题</View>
                    <View className='question-card' onClick={this.showQuestionPopup.bind(this)}>
                        <Image src={require('@/assets/icons/mine/xiaoyi_answer_sheet.svg')}></Image>
                        <Text className='question-num'>{currentInex + 1}</Text>
                        <Text>{`/${questions.length}`}</Text>
                    </View>
                </View>
                <View className='question'>
                    <ScrollView
                        className='scrollview'
                        scrollX
                        scrollY
                        scrollWithAnimation
                        scrollLeft={scrollLeft}
                        pagingEnabled
                        enhanced
                        enableFlex
                        onScroll={this.onScrollEndd.bind(this)}
                    // style={scrollStyle}
                    >
                        {
                            questions.map((item, index) => {
                                var sureOptions = item['question']['options'].find((optionsItem, index) => {
                                    return optionsItem['optScore'] > 0
                                })

                                // item['question']['keywords'] = '基金;基金公司;银行'
                                // 使用正则表达式匹配文本并将匹配到的部分包裹在span标签中，并添加样式
                                var keywords = item['question']['keywords'].split(';')
                                const formattedText = item['question']['questionContent'].replace(
                                    new RegExp(`(${keywords.join('|')})`, 'gi'),
                                    '&;&$1&;&'
                                );
                                // 将符合关键词的部分替换为自定义组件
                                const text = formattedText.split('&;&')
                                // console.log(text)
                                const replacedText = text.map((word, index) => {
                                    if (keywords.includes(word)) {
                                        return <View className="title-highlight" data-text="$1" onClick={(e) => this.handleSpanClick(word)}>{word}</View>
                                    }
                                    return <Text key={index}>{word} </Text>
                                })
                                return <View className='question-item'>
                                    <View className='question-title'>
                                        {replacedText}
                                    </View>
                                    {/* <View className='question-title'>{item['question']['questionContent']}</View> */}
                                    <View className='question-option'>
                                        {
                                            (item['question']['options']).map((optionsItem, index) => {
                                                var isSure = 0; // 0 初始  1 正确  2错误
                                                if (optionsItem['optScore'] > 0) {
                                                    isSure = 1;
                                                }
                                                if (item['answer']['optValue'] !== undefined && optionsItem['optValue'] === item['answer']['optValue'] && optionsItem['optScore'] === 0) {
                                                    isSure = 2;
                                                }
                                                return <View className={`question-option-item ${isSure === 1 ? 'question-option-item-sure' : (isSure === 2 ? 'question-option-item-wrong' : '')}`}>
                                                    <Text>{`${optionsItem['optValue']}.`}</Text>
                                                    <Text>{optionsItem['optContent']}</Text>
                                                </View>
                                            })
                                        }
                                    </View>
                                    <View className='question-span'></View>
                                    <View className='question-answer'>
                                        <Text className='title'>答案解析</Text>
                                        <View className='sure-answer'>{`正确答案：${sureOptions['optValue']}`}</View>
                                        <Text className='anser-analysis'>{item['question']['textParsing']}</Text>
                                    </View>
                                </View>
                            })
                        }
                    </ScrollView>

                    <Popup show={showPopUP} position='bottom' onClose={this.onClose.bind(this)}>
                        <View className='pop-question-num'>
                            {
                                questions.map((item, index) => {
                                    var tag = ''
                                    if (item['answer'] !== undefined) {
                                        if (item['answer']['optScore'] > 0) {
                                            tag = 'pop-question-num-item-sure'
                                        } else {
                                            tag = 'pop-question-num-item-wrong'
                                        }
                                    }
                                    // ${tag}
                                    return <View className={`pop-question-num-item `} onClick={(e) => this.gotoIndexPage(index)}>{index + 1}</View>
                                })
                            }
                        </View>
                    </Popup>

                    <Popup show={showXiaoyiPopUP} position='bottom' onClose={this.onXiaoyiClose.bind(this)}>
                        <View className='xiaoyi-pop-up'>
                            {
                                <Text className='xiaoyi-pop-up-title'>{xiaoyiPopupType === 1 ? '小以AI答案提示' : '小以概念百科'}</Text>
                            }
                            {
                                xiaoyiPopupType === 1 ? <Text className='xiaoyi-pop-up-context'>{xiaoyiCurrentAnswerxi.length > 0 ? xiaoyiCurrentAnswerxi : (requestCount > 10 ? '人类的问题太多了！我需要休息一下再回复您' : '小以正在思考如何回答中...')}</Text> :
                                    <View className='xiaoyi-pop-up-context'>
                                        <Text className='xiaoyi-pop-up-baike'>{xiaoyiNounCurrentNoun}</Text>
                                        <Text>{(xiaoyiNounPairMap[xiaoyiNounCurrentNoun] !== undefined && xiaoyiNounPairMap[xiaoyiNounCurrentNoun].length > 0) ? xiaoyiNounPairMap[xiaoyiNounCurrentNoun] : (requestCount > 10 ? '人类的问题太多了！我需要休息一下再回复您' : '小以正在思考如何回答中...')}</Text>
                                    </View>
                            }
                            <></>
                            <View className='xiaoyi-pop-up-line'></View>
                            <Text className='xiaoyi-pop-up-desc'>此内容根据小以自动生成，答案仅供参考</Text>
                        </View>


                    </Popup>
                    <Toast></Toast>
                </View>

            </View>
        );
    }
}


export default XiaoYiAnalysis;